package ar.com.gals.controller;

import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import ar.com.gals.constants.Page;
import ar.com.gals.error.GalsException;
import ar.com.gals.model.MargenModel;

@Controller
@RequestMapping(value = "/Edicion/Margen")
public class MargenController extends AbstractController {

	@PreAuthorize("hasRole('EDMARG')")
	@RequestMapping(method = RequestMethod.GET)
    public String modificarMargen(Model model) {
		try 
		{
			model.addAttribute("model", new MargenModel(this.getUsuario()));
			model.addAttribute("action", "M");
			return Page.EDICION_MARGEN;
		}
		catch(GalsException ex) {
			model.addAttribute("messageResult", ex.getErrors().get(0).getDescripcion());
			return "redirect:" + Page.URL_INIT;
		}
    }
	
	
	@PreAuthorize("hasRole('EDMARG')")
	@RequestMapping(method = RequestMethod.POST)
    public String modificarMargen(
    		@ModelAttribute("model") @Valid MargenModel margenModel, 
    		BindingResult result, 
    		Model model)
	{
		try 
		{
			if(result.hasErrors() || margenModel.hasErrors()) {
				model.addAttribute("model", margenModel);
				model.addAttribute("action", "M");
				return Page.EDICION_MARGEN;
			}
			
			margenModel.modificarMargen(this.getUsuario());
		}
		catch(GalsException ex) {
			model.addAttribute("model", margenModel);
			model.addAttribute("errors", ex.getErrors());
			model.addAttribute("action", "M");
			return Page.EDICION_MARGEN;
		}		
		
		model.addAttribute("messageResult", "El margen de ganancia se modific&oacute; exitosamente");
		return "redirect:" + Page.URL_INIT;
    }
}
